package com.central.apps.handler;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.controller.BizNumberController;
import com.central.app.service.HandlerService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Component
public class LubricantstandardHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;
    @Autowired
    private BizNumberController bizNumberController;


    public void timeTaskToLub(){
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        String currentDate = fmt.format(new Date());
        List<Object> lubaddList = new ArrayList<Object>();
        List<Map<String, Object>> lubricantsList=handlerService.findBySql("select id,lubstdnum,lubricantcycle,starttime,isstart from bl_lubricantstandard");
        if (lubricantsList!=null) {
            for (int k = 0; k < lubricantsList.size(); k++) {
                Map<String, Object> lubMap=lubricantsList.get(k);
                String id = MapUtil.getStr(lubMap, "id");
                String lubstdnum = MapUtil.getStr(lubMap, "lubstdnum");
                String lubricantcycle = MapUtil.getStr(lubMap, "lubricantcycle");
                String starttime = MapUtil.getStr(lubMap, "starttime");
                String isstart = MapUtil.getStr(lubMap, "isstart");
                if (isstart.equals("1")) {
                    if (lubricantcycle.equals("D")) {
                lubaddList.add(id);
                    } else if (lubricantcycle.equals("M")){
                        if (starttime != null && !"".equals(starttime)) {
                            starttime = starttime.replaceAll("[[\\s-:punct:]]", "");
                            boolean flag = starttime.equals(currentDate.trim());
                            if (flag) {
                                lubaddList.add(id);

                            }

                        }
                    }else if (lubricantcycle.equals("S")){
                        lubaddList.add(id);
                    }
                }

            }
            timeTaskToLub(lubaddList);
        }


    }
    public void timeTaskToLub(List<Object> lubaddList) {
        List<Object> startFlowList = new ArrayList<Object>();
        if (CollectionUtils.isNotEmpty(lubaddList)) {
            SimpleDateFormat sdftime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
            SimpleDateFormat datefmt = new SimpleDateFormat("yyyy-MM-dd");
            String numFormat = "%06d";//数字格式
            String createtime = sdftime.format(new Date());
            for (int k = 0; k < lubaddList.size(); k++) {

                String lubaddId = (String) lubaddList.get(k);
                String lubstdnum = null;
//                String newNum = fmt.format(new Date());
                String newNum = bizNumberController.findNumByMark("lubricanttaskApp", "bl_lubricanttask", null, new HashMap<String, Object>());
                List<Map<String, Object>> lubteList = handlerService.findBySql("select lubstdnum,inspectionname,workdivision,lubricanttype,lubricantstaffgroup from bl_lubricantstandard where id ='" + lubaddId + "'");
                String add2 = "select lubstdnum,'" + newNum + "'as lubtasknum,inspectionname,workdivision,lubricanttype,lubricantstaffgroup,lubricantstaff,deptcode,0,1,'" +createtime+"' as createtime from bl_lubricantstandard where id ='" + lubaddId + "'";
                if (CollectionUtils.isNotEmpty(lubteList) && MapUtil.isNotEmpty(lubteList.get(0))) {
                    List<Map<String, Object>> insliList=null;

                    Map lubteMap = lubteList.get(0);
                    lubstdnum = MapUtil.getStr(lubteMap, "lubstdnum");
                    String starttime=MapUtil.getStr(lubteMap, "starttime");;
                    Integer lubricantcycleunit = MapUtil.getInt(lubteMap, "lubricantcycleunit");
                    String lubricantcycle = MapUtil.getStr(lubteMap, "lubricantcycle");
                    try{
                        String addSql = "insert into bl_lubricanttask(lubstdnum,lubtasknum,inspectionname,workdivision,lubricanttype,lubricantstaffgroup,lubricantstaff,deptcode,status,createuser,createtime)";
                        handlerService.updateBySql(addSql + add2);
                        insliList = handlerService.findBySql("select id from bl_lubricanttask where lubtasknum='" + newNum+ "' ");
                        if (insliList.size()>0) {
                            Integer addid = MapUtil.getInt(insliList.get(0), "id");
                            startFlowList.add(addid);
                        }
                        //为什么要再查一遍呢  直接用newNum不好吗 刚新增了肯定有吧
//                    List<Map<String, Object>> lubline2List = handlerService.findBySql("select lubtasknum from bl_lubricanttask where lubstdnum='"+lubstdnum+"' ");
//                    if (lubline2List!=null){
//                        Map<String, Object> lubline2Map=lubline2List.get(0);
//                        String lubtasknum=MapUtil.getStr(lubline2Map,"lubtasknum");

                        //复制子表
                        List<Map<String, Object>> lublineList = handlerService.findBySql("select lubstdnum,inspectionassetnum,inspectionassetname,lubricantpart,lubricantmethod,greasegrade,lubricantpoint from bl_lubricantstandardline where lubstdnum = '" + lubstdnum + "'");

                        if (lublineList.size() > 0) {
                            Map<String, Object> lineMap=lublineList.get(0);
                            String lubstdnum2 = MapUtil.getStr(lineMap, "lubstdnum");
                            String lublineSql = "insert into bl_lubricanttaskline(lubricantstandrad,lubstdnum,inspectionassetnum,inspectionassetname,lubricantpart,lubricantmethod,greasegrade,lubricantpoint,lubtasknum,deptcode,status,createuser,createtime)";
                            String lublineSql2 = "select lubricantstandrad,lubstdnum,inspectionassetnum,inspectionassetname,lubricantpart,lubricantmethod,greasegrade,lubricantpoint,'"+newNum+"',deptcode,0,1,'" +createtime+"' as createtime from bl_lubricantstandardline where lubstdnum = '" + lubstdnum2 + "'";
                            handlerService.updateBySql(lublineSql + lublineSql2);
                        }
//                    }
                    }
                    catch (Exception e){
                        String error_log = "insert into error_log(ywnum,message,createtime) values('"+lubstdnum+"','"+createtime+"','"+"启动流程失败！')" ;
                        handlerService.updateBySql(error_log);
                    }
                    try {
                        if (CollectionUtils.isNotEmpty(lubteList))
                            timeTStartFlow(MapUtils.getLong(insliList.get(0), "id"), "lubricanttaskApp");
                        else{
                            String error_log = "insert into error_log(ywtype,message,createtime) values('启动流程','未查出bl_lubricantstandard数据！','"+createtime+"')" ;
                            handlerService.updateBySql(error_log);
                        }
                    }
                    catch (Exception e)
                    {
                        String error_log = "insert into error_log(ywid,ywtype,message,createtime) values('"+MapUtils.getLong(insliList.get(0), "id")+"','启动流程','启动流程失败！','"+createtime+"')" ;
                        handlerService.updateBySql(error_log);
                    }

                    //更新周期
                    if (starttime != null) {
                        try {
                            Date starttime2 = datefmt.parse(starttime);
                            if (null != lubricantcycle && lubricantcycle.equals("M")) {
                                Calendar cal = Calendar.getInstance();
                                cal.setTime(starttime2);
                                cal.add(Calendar.MONTH, lubricantcycleunit);
                                Date Nextdate = cal.getTime();
                                handlerService.updateBySql("update bl_lubricantstandard set starttime='" + Nextdate + "' where id ='" + lubaddId + "' ");
                            } else if (null != lubricantcycle && lubricantcycle.equals("D")) {
                                Calendar cal = Calendar.getInstance();
                                cal.setTime(starttime2);
                                cal.add(Calendar.DATE, lubricantcycleunit);
                                Date Nextdate = cal.getTime();
                                handlerService.updateBySql("update bl_lubricantstandard set starttime='" + Nextdate + "' where id ='" + lubaddId + "' ");
                            } else if (null != lubricantcycle && lubricantcycle.equals("S")) {
                                Calendar cal = Calendar.getInstance();
                                cal.setTime(starttime2);
                                cal.add(Calendar.DATE, 1);
                                Date Nextdate = cal.getTime();
                                handlerService.updateBySql("update bl_lubricantstandard set starttime='" + Nextdate + "' where id ='" + lubaddId + "' ");
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                            String error_log = "insert into error_log(ywid,ywtype,message,createtime) values('"+lubaddId+"','更新周期','"+"更新周期异常"+"','"+createtime+"')" ;
                            handlerService.updateBySql(error_log);
                        }
                    }


                }
                else{
                    //非正常状态
                    String error_log = "insert into error_log(message,createtime) values('"+"CollectionUtils.isNotEmpty(lubteList) && MapUtil.isNotEmpty(lubteList.get(0)) 不成立"+"','"+createtime+"')" ;
                    handlerService.updateBySql(error_log);
                }
            }
//            timeTStartFlow(startFlowList,"lubricanttaskApp");
        }

    }
    public void timeTStartFlow(Long id, String app) throws  Exception{
        FlowOpinion flowOpinion = new FlowOpinion();
        flowOpinion.setOpId("admin");
        flowOpinion.setOpName("超级管理员");
//        try {
        handlerService.forcibleStart(app, id, flowOpinion);
//        } catch (Exception e) {
//        }
    }

//    public void timeTStartFlow(List<Object> startIdList,String app) {
//        for (int k = 0; k < startIdList.size(); k++) {
//            Integer id = (Integer) startIdList.get(k);
//            FlowOpinion flowOpinion = new FlowOpinion();
//            flowOpinion.setOpId("admin");
//            flowOpinion.setOpName("超级管理员");
//            try {
//                handlerService.forcibleStart(app, Long.valueOf(id.toString()),flowOpinion);
//            }catch (Exception e){
//            }
//
//        }

//    }

    /**
     * 润滑任务单自定义力流程节点审批人
     * @param app
     * @param id
     * @param flowNode
     * @param vars
     * @return
     * @throws Exception
     */
    @Override
    public String addFlowCandidate(String app, Long id, FlowNode flowNode, Map<String, Object> vars) throws Exception {
        if("zx".equals(flowNode.getId())){
            List<Map<String, Object>> list = handlerService.findBySql("select * from bl_lubricanttask where id=" + id);
            String lubricantstaffgroup= MapUtils.getString(list.get(0),"lubricantstaffgroup");
            String lubricantstaff=MapUtils.getString(list.get(0),"lubricantstaff");

            String person="";

            if(lubricantstaffgroup!=null && !"".equals(lubricantstaffgroup)){
                List<Map<String, Object>> persons = handlerService.findBySql("select personid from bl_person where  workgroup='"+lubricantstaffgroup+"'");
                if (CollectionUtils.isNotEmpty(persons)) {
                    //人员以逗号隔开
                    StringJoiner sj = new StringJoiner(",", "", "");
                    for (Map<String, Object> username : persons) {
                        sj.add(MapUtils.getString(username, "personid"));
                    }
                    person = sj.toString();
                }
            }else{
                Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
                Matcher m = p.matcher(lubricantstaff);
                if (!m.find()) {
                    person=lubricantstaff;
                }
            }
            if(person==null|| "".equals(person)){
                person="admin";
            }
            return person;
//            String type=MapUtils.getString(list.get(0),"workdivision");//润滑任务单类型，操作、维修、点检
//            String executer = "";
//            List<Map<String, Object>> personList = null;
//            if("操作".equals(type)){
//                personList = handlerService.findBySql(" select concat_ws(',',equipmentperson1,equipmentperson2,equipmentperson3,  " +
//                        "equipmentperson4,equipmentperson5,equipmentperson6,equipmentperson7,equipmentperson8,equipmentperson9,  " +
//                        "equipmentperson10,equipmentperson11,equipmentperson12,equipmentperson13,equipmentperson14,equipmentperson15,  " +
//                        "equipmentperson16,equipmentperson17,equipmentperson18,equipmentperson19,equipmentperson20) name from bl_asset where assetnum in (  " +
//                        "  select inspectionassetnum from bl_inspectionline where inspectionnum in (select inspectionnum from bl_inspection where id=" + id + ")) ");
//
//            }else if("维修".equals(type)){
//                personList = handlerService.findBySql("   select concat_ws(',',overhaulperson1,overhaulperson2,overhaulperson3,overhaulperson4) name" +
//                        "  from bl_asset where assetnum in (  " +
//                        "  select inspectionassetnum from bl_inspectionline where inspectionnum in (select inspectionnum from bl_inspection where id=" + id + ")) ");
//
//            }else if("点检".equals(type)){
//                personList = handlerService.findBySql("   select concat_ws(',',checkperson1,checkperson2,checkperson3,checkperson4) name " +
//                        " from bl_asset where assetnum in (  " +
//                        "  select inspectionassetnum from bl_inspectionline where inspectionnum in (select inspectionnum from bl_inspection where id=" + id + ")) ");
//
//            }
//            if (CollectionUtils.isNotEmpty(personList)) {
//                //人员以逗号隔开
//                StringJoiner sj = new StringJoiner(",");
//                for (Map<String, Object> name : personList) {
//                    sj.add(MapUtils.getString(name, "name"));
//                }
//                executer = sj.toString();
//            }
//
//            return executer;
        }

        return super.addFlowCandidate(app, id, flowNode, vars);
    }
}


